<?php
namespace app\api\controller\vppz;


use think\Cache;


use \app\admin\model\vppz\MedicationPlan as MedicationPlanModel;
use \app\admin\model\vppz\MedicalInformation as MedicalInformationModel;
use \app\admin\model\Crontab as CrontabModel;

use \addons\vppz\library\Vpower;

class Medicalmanage extends App
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $guidances = array(
            'before'=>'餐前',
            'after'=>'餐后',
            'empty'=>'空腹',
            'with'=>'随餐服用 ',
            'sleep'=>'睡前',
        );

    public function _initialize(){
        parent::_initialize();
        $this->MedicationPlanModel = new MedicationPlanModel;
        $this->MedicalInformationModel = new MedicalInformationModel;
        $this->CrontabModel = new CrontabModel;
    }
    public function getMedicalInfo(){
        $family_id = input('family_id','');
        $note = $this->MedicalInformationModel->where([
            'family_id'=>$family_id
        ])->whereNull('deletetime')->group('type')
            ->order('type','asc')
            ->column('type');
        $this->success('成功',$note);
    }
    //获取医药资料夹
    public function getMedicalNote(){
        $type = input('type','outpatient');
        $family_id = input('family_id','');
        $page = input('page',1);
        $size = input('size',10);
        $note = $this->MedicalInformationModel->where([
            'type'=>$type,
            'family_id'=>$family_id
        ])->whereNull('deletetime')->select();
        $date = [];
        $res = [];
        if(empty($note)===FALSE){
            foreach ($note as &$v){
                $images = json_decode($v['image'],true);
                foreach ($images as &$imagev){
                    $imagev = \addons\vppz\library\Vpower::dourl($imagev);
                }
                $v['images'] = $images;
                if(!in_array($v['date'],$date)){
                    array_push($date,$v['date']);
                    array_push($res,array(
                        'date'=>$v['date'],
                        'records'=>[$v]
                    ));
                }else{
                    foreach ($res as &$resv){
                        if($resv['date'] == $v['date']){
                            $rescords = $resv['records'];
                            array_push($rescords,$v);
                            $resv['records'] = $rescords;
                        }
                    }
                }

            }
        }
        $total = count($res);
        $note = array_slice($res,($page-1)*$size,$size);
        $res = array(
            'list'=>$note,
            'total'=>$total
        );
        $this->success('成功',$res);
    }
    public function updateSaveImage(){
        $type = input('type','outpatient');
        $hospital = input('hospital','');
        $title = input('title','');
        $visitDate = input('visitDate','');
        $image = input('image','');
        $family_id = input('family_id','');
        $data = array(
            'type'=>$type,
            'image'=>html_entity_decode($image),
            'date'=>$visitDate,
            'family_id'=>$family_id,
            'title'=>$title,
            'hospital_name'=>$hospital,
        );
        $ret = $this->MedicalInformationModel->save($data);
        if($ret){
            $id = $this->MedicalInformationModel->id;
            $info = $this->MedicalInformationModel->where([
                'id'=>$id
            ])->find();
            $this->success('提交成功',$info);
		}else{
            $this->error('抱歉，提交失败，重试看看呢');
        }

    }
    //删除
     public function delMedicalNote(){
        $id = input('id','');
        $res = $this->MedicalInformationModel->where([
            'id'=>$id
        ])->delete();
        $this->success('成功',$res);
    }
    //获取用药计划
    public function getMedicalPlan(){
        $family_id = input('family_id','');
        $upcomingnote = $this->MedicationPlanModel->where([
            'family_id'=>$family_id,
            'status'=>0
        ])->whereNull('deletetime')->select();
        if(empty($upcomingnote) === FALSE){
            foreach ($upcomingnote as &$v){
                $times = json_decode($v['time'],true);
                sort($times);
                $v['times'] = $times;
                if(empty($v['guidance']) === FALSE) {
                    $v['guidancename'] = $this->guidances[$v['guidance']];
                }else{
                    $v['guidancename'] = '餐前';
                    $v['guidance'] = 'before';
                }
            }
        }
        $ongoingnote = $this->MedicationPlanModel->where([
            'family_id'=>$family_id,
            'status'=>1
        ])->whereNull('deletetime')->select();
        if(empty($ongoingnote) === FALSE){
            foreach ($ongoingnote as &$v){
                $times = json_decode($v['time'],true);
                sort($times);
                $v['times'] = $times;
                if(empty($v['guidance']) === FALSE) {
                    $v['guidancename'] = $this->guidances[$v['guidance']];
                }else{
                    $v['guidancename'] = '餐前';
                    $v['guidance'] = 'before';
                }
            }
        }
        $completenote = $this->MedicationPlanModel->where([
            'family_id'=>$family_id,
            'status'=>2
        ])->whereNull('deletetime')->select();
        if(empty($completenote) === FALSE){
            foreach ($completenote as &$v){
                $times = json_decode($v['time'],true);
                sort($times);
                $v['times'] = $times;if(empty($v['guidance']) === FALSE) {
                    $v['guidancename'] = $this->guidances[$v['guidance']];
                }else{
                    $v['guidancename'] = '餐前';
                    $v['guidance'] = 'before';
                }
            }
        }
        $res = array(
            'ongoingPlans'=>$ongoingnote,
            'upcomingPlans'=>$upcomingnote,
            'completedPlans'=>$completenote
        );
        $this->success('成功',$res);
    }
    public function getMedicalPlanDetail(){
        $id = input('id','');
        $note = $this->MedicationPlanModel->where([
            'id'=>$id
        ])->find();
        $note['times'] = json_decode($note['time'],true);
        $this->success('成功',$note);
    }
    public function delMedicalPlan(){
        $id = input('id','');
        $note = $this->MedicationPlanModel->where([
            'id'=>$id
        ])->delete();
        $crontab = $this->CrontabModel->where([
            'plan_id'=>$id
        ])->find();
        if(empty($crontab) === FALSE){
            $this->CrontabModel->where([
                'plan_id'=>$id
            ])->delete();
        }
        $this->success('成功',$note);
    }
    public function getMedicalPlanOnGoing(){
        $family_id = input('family_id','');
        $ongoingnote = $this->MedicationPlanModel->where([
            'family_id'=>$family_id,
            'status'=>1
        ])->whereNull('deletetime')->select();
        if(empty($ongoingnote) === FALSE){
            foreach ($ongoingnote as &$v){
                $times = json_decode($v['time'],true);
                sort($times);
                $v['times'] = $times;if(empty($v['guidance']) === FALSE) {
                    $v['guidancename'] = $this->guidances[$v['guidance']];
                }else{
                    $v['guidancename'] = '餐前';
                    $v['guidance'] = 'before';
                }
            }
        }
        $this->success('成功',$ongoingnote);
    }
    public function createMedicalPlanData(){
        $json = file_get_contents("php://input");
        $mine=$this->_mine;
        // 将JSON字符串解码为PHP数组或对象
        $data = json_decode($json, true);
        $info = $this->MedicationPlanModel->where([
            'family_id'=>$data['family_id']
        ])->find();
        $time = strtotime($data['start_date']) + $data['length'] * 86400;
        $end_time = date('Y-m-d',$time);
        $status = 0;
        if(strtotime($data['start_date']) > time()){
            $status = 0;
        }elseif (strtotime($data['start_date']) < time() && $time > time()){
            $status = 1;
        }else{
            $status = 2;
        }
        $resdata = array(
            'family_id'=>$data['family_id'],
            'medication_name'=>$data['medication_name'],
            'frequency'=>$data['frequency'],
            'guidance'=>$data['guidance'],
            'length'=>$data['length'],
            'duration'=>$data['duration'],
            'metering'=>$data['metering'],
            'metering_unit'=>$data['metering_unit'],
            'method'=>$data['method'],
            'num'=>$data['num'],
            'remark'=>$data['remark'],
            'scheme'=>$data['scheme'],
            'start_date'=>$data['start_date'],
            'end_time'=>$end_time,
            'status'=>$status,
            'time'=>json_encode($data['times']),
        );
        if(isset($data['id']) && $data['id'] > 0){
            $id = $data['id'];
            $ret = $this->MedicationPlanModel->where([
                'id'=>$id
            ])->update($resdata);
            //判断是否有正在执行的任务  有则删除
            $crontab = $this->CrontabModel->where([
                'family_id'=>$data['family_id'],
                'plan_id'=>$id
            ])->find();
            if(empty($crontab) === FALSE){
                $this->CrontabModel->where([
                    'family_id'=>$data['family_id'],
                    'plan_id'=>$id
                ])->delete();
            }
        }else{
            $ret = $this->MedicationPlanModel->save($resdata);
            $id = $this->MedicationPlanModel->id;
        }

		if($ret){
            $datainfo = $this->MedicationPlanModel->where([
                'id'=>$id
            ])->find();
            $datainfo['times'] = json_decode($datainfo['time'],true);
            if($status < 2) {
                $starttime = datetime(strtotime($data['start_date']),'Y-m-d H:i:s');
                $endtime = datetime($time,'Y-m-d H:i:s');
                $next_time = time();
                if($data['scheme'] == 0){
                    //每天几次
                    $t = $datainfo['times'];
                    sort($t);
                    foreach ($t as &$vtime) {
                        if(strtotime($datainfo['start_date'] . ' ' . $vtime) >= time()){
                            $next_time = strtotime($datainfo['start_date'] . ' ' . $vtime);
                            break;
                        }
                    }
                }elseif ($data['scheme'] == 1){
                    //几天一次
                    if(strtotime($datainfo['start_date'] . ' ' . $datainfo['times'][0]) <= time()){
                        $next_time = strtotime($datainfo['start_date'] . ' ' . $datainfo['times'][0]) + $datainfo['num']*86400;
                    }else{
                        $next_time = strtotime($datainfo['start_date'] . ' ' . $datainfo['times'][0]);
                    }
                }else{
                    //几小时一次
                    if($status == 0){
                        $next_time = strtotime($datainfo['start_date'] . ' ' . $datainfo['times'][0]);
                    }else if ($status == 1){
                        $next_time = strtotime($datainfo['start_date'] . ' ' . $datainfo['times'][0]) + $datainfo['num']*3600;
                    }
                }
                //添加定时任务
                $crontabData = array(
                    'user_id' => $mine['id'],
                    'family_id' => $data['family_id'],
                    'plan_id' => $id,
                    'start_date' => $starttime,
                    'end_date' => $endtime,
                    'type' => 1,
                    'next_time' => $next_time
                );
                $this->CrontabModel->save($crontabData);
            }

            $this->success('提交成功',$datainfo);
		}else{
            $this->error('抱歉，提交失败，重试看看呢');
        }
    }
}
